<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Test</title>
		<script src="assets/js/jquery.min.js"></script>
		<link rel="stylesheet" href="assets/plyr/plyr.css" />
		<!-- CSV parser -->
		<script src="assets/js/papaparse.min.js"></script>
		<style>
		* {
			margin:0;
			padding:0;
		* }
		/* So that video fits perfectly inside container */
		body, html, .player-container, .plyr {
			height: 100%;
		}
		.plyr__video-embed {
			padding-bottom:0 !important;
			height:100%;
		}
		</style>
	</head>
	<body>

		<div class="player-container"></div>


		<script src="assets/plyr/plyr.min.js"></script>
		<script type="text/javascript">
			var player=null; // ensure global access later

			// CSV columns
			const COL_COUNTRY=0;
			const COL_VIDEO_TITLE=1;
			const COL_VIDEO_URL=2;
			const COL_LISTING_DATE=3;

			function getYoutubeId(url){
				// source: https://stackoverflow.com/a/8260383
				// TODO: Add other video providers as well, such as Vimeo.
				var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
				var match = url.match(regExp);
				return (match&&match[7].length==11)? match[7] : false;
			}

			function getPlyrHtml(videourl) {
				var videoId=getYoutubeId(videourl);
				// TODO: Adopt to other video providers as well, such as Vimeo.
				return '			<div class="plyr__video-embed" id="player"> \
				<iframe src="https://www.youtube.com/embed/'+videoId+'?origin=https://plyr.io&amp;iv_load_policy=3&amp;modestbranding=1&amp;playsinline=1&amp;showinfo=0&amp;rel=0&amp;enablejsapi=1" \
					allowfullscreen \
					allowtransparency \
					allow="autoplay" \
				></iframe> \
			</div>';
			}

			function changeVideo(videoUrl) {
				if (player==null) {
					initiatePlayer(videoUrl);
				} else {
					player.source = {
						type: 'video',
						sources: [
							{
								src: getYoutubeId(videoUrl),
								provider: 'youtube',
							},
						],
					};
				}
			}

			function initiatePlayer(initialUrl) {
				// get the fallback code
				$('.player-container').html(getPlyrHtml(initialUrl));

				// sources:
				// https://stackoverflow.com/a/53682741
				// https://github.com/sampotts/plyr/blob/master/controls.md
				const controls = [
					//'play-large', // The large play button in the center
					//'restart', // Restart playback
					'rewind', // Rewind by the seek time (default 10 seconds)
					'play', // Play/pause playback
					'fast-forward', // Fast forward by the seek time (default 10 seconds)
					'progress', // The progress bar and scrubber for playback and buffering
					'current-time', // The current time of playback
					'duration', // The full duration of the media
					'mute', // Toggle mute
					'volume', // Volume control
					'captions', // Toggle captions
					'settings', // Settings menu
					//'pip', // Picture-in-picture (currently Safari only)
					//'airplay', // Airplay (currently Safari only)
					//'download', // Show a download button with a link to either the current source or a custom URL you specify in your options
					'fullscreen' // Toggle fullscreen
				];
				player = new Plyr(document.getElementById('player'),{
					autoplay: true,
					controls: controls,
					settings: ['captions', 'quality', 'speed', 'loop']
				});

				player.on('ready', event => {
					// detach events set by the stubborn listeners.js
					// source: https://stackoverflow.com/a/39026635
					document.querySelector("button[data-plyr='rewind']").outerHTML = document.querySelector("button[data-plyr='rewind']").outerHTML;
					document.querySelector("button[data-plyr='fast-forward']").outerHTML = document.querySelector("button[data-plyr='fast-forward']").outerHTML;

					$("button[data-plyr='rewind']").on( "click", function(){
						playPreviousItem();
					});
					$("button[data-plyr='fast-forward']").on( "click", function(){
						playNextItem();
					});
				});

				player.on('ended', event => {
					videoEnded();
				});
			}

			// Playlist related
			var playlistData=null;
			var currentIndex=null; // zero based
			var playlistTotalItems=null; // zero based
			function loadPlaylist(filename,autoplay=true) {
				fetch(filename)
					.then(response => response.text())
					.then(text => {
						//console.log(text)
						//const data = Papa.parse(text);
						playlistData = Papa.parse(text).data;
						//$('#output').html( JSON.stringify(data, null, 2) );
						console.log(playlistData);
						console.log(playlistData[0][COL_VIDEO_URL]);
						changeVideo(playlistData[0][COL_VIDEO_URL]);
						currentIndex=0;
						playlistTotalItems=playlistData.length;
						})
			}
			function playNextItem() {
				if (playlistData != null) {
					if (currentIndex != playlistTotalItems-1) { // if not playing last item
						changeVideo(playlistData[currentIndex+1][COL_VIDEO_URL]);
						currentIndex++;
					}
				}
			}
			function playPreviousItem() {
				if (playlistData != null) {
					if (currentIndex != 0) { // if not playing last item
						changeVideo(playlistData[currentIndex-1][COL_VIDEO_URL]);
						currentIndex--;
					}
				}
			}
			// Runs when the video has finished playing
			function videoEnded() {
				playNextItem();
			}

			$(function(){
				loadPlaylist("./data/ajob-01.csv",true);


			});



		</script>
	</body>
</html>